import React, { Component } from 'react'
import axios from 'axios'
export default class MovieList extends Component {
  constructor() {
    super()
    this.state = {
      leixing: 0,
      movieList: []
    }
  }


  /*
    首先从外部组件通过该方法的第一个参数拿到值，然后可以通过return的方法将外部的值，直接赋值给本组件state
  */
  static getDerivedStateFromProps(nextProps, prevState) {
    console.log('----getDerivedStateFromProps--------------');
    const { type } = nextProps
    if(prevState.leixing!=type){
      return {
        leixing: type,
      }
    }
    return null;
   
  }
  componentDidUpdate(prevProps,prevState) {
    if(prevState.leixing===this.state.leixing){
      return;
    }
    console.log('---------componentDidUpdate--------------');
    if (this.state.leixing === 1) {
      axios.get('https://www.fastmock.site/mock/4441a79ad5f884f83b784cf4c588bdb6/movies/getHotMovies').then(res => {
        console.log('正在热映', res.data.movies);
        this.setState({
          movieList: res.data.movies
        })
      })
    } else if (this.state.leixing == 2) {
      axios.get('https://www.fastmock.site/mock/4441a79ad5f884f83b784cf4c588bdb6/movies/getUpCommingMovies').then(res => {
        console.log('即将热映', res.data.movies);
        this.setState({
          movieList: res.data.movies
        })
      })
    }
  }
  render() {
    return (
      <div>
        <ul>
          {
            this.state.movieList.length > 0 && this.state.movieList.map(item => <li key={item.id}>
              {item.title}
            </li>)
          }
        </ul>
      </div>
    )
  }
}
